package ai.leinao.notify.core;

import ai.leinao.notify.core.enums.NotifyType;
import ai.leinao.notify.core.provider.NotifierProvider;
import lombok.NonNull;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 抽象通知管理器
 *
 * @author zhong.wang
 * @date 2025/7/8
 */
public abstract class AbstractNotifierRegistry implements NotifierRegistry {
    /**
     * 通知供应商容器
     * key: notifyType
     * value: key: providerId value: notifierProvider
     */
    protected final Map<String, Map<String, NotifierProvider>> notifyProviderMap = new ConcurrentHashMap<>();


    /**
     * 通知器容器
     * key: 通知器id
     * value: notifier
     */
    protected final Map<String, Notifier> notifierMap = new ConcurrentHashMap<>();


    /**
     * 根据通知类型和通知器ID获取通知属性
     *
     * @return
     */
    protected abstract NotifyProperties getNotifyProperties(NotifyType notifyType, String id);

    /**
     * 注册通知供应商
     *
     * @param provider
     */
    protected void registerProvider(NotifierProvider provider) {
        if(!notifyProviderMap.containsKey(provider.getNotifyType().getType())){
            notifyProviderMap.put(provider.getNotifyType().getType(), new ConcurrentHashMap<>());
        }
        notifyProviderMap.get(provider.getNotifyType().getType()).put(provider.getProvider(), provider);
    }

    /**
     * 获取通知器
     *
     * @param notifyType 通知器类型
     * @param notifyId 通知器ID
     * @return
     */
    @Override
    @NonNull
    public Notifier getNotifier(@NonNull NotifyType notifyType, @NonNull String notifyId) {
        if(notifierMap.containsKey(notifyId)){
            return notifierMap.get(notifyId);
        }
        NotifyProperties properties = getNotifyProperties(notifyType, notifyId);
        if(Objects.nonNull(properties)){
            Notifier notifier = createNotifier(properties);
            notifierMap.put(notifyId, notifier);
            return notifier;
        }
        return null;
    }

    /**
     * 创建通知器
     *
     * @param properties 通知器属性
     * @return
     */
    @Override
    @NonNull
    public Notifier createNotifier(@NonNull NotifyProperties properties) {
        if(!notifyProviderMap.containsKey(properties.getNotifyType().getType())){
            throw new UnsupportedOperationException("不支持该通知类型:"+ properties.getNotifyType().getType());
        }else{
            Map<String, NotifierProvider> providerMap = notifyProviderMap.get(properties.getNotifyType().getType());
            if(!providerMap.containsKey(properties.getProvider())){
                throw new UnsupportedOperationException("不支持该供应商:"+ properties.getProvider());
            }else{
                NotifierProvider provider = providerMap.get(properties.getProvider());
                Notifier<?> notifier = provider.createNotifier(properties);
                return notifier;
            }
        }
    }



}
